package com.elegantmall.controller;

import cn.dev33.satoken.util.SaResult;
import com.elegantmall.pojo.CartPojo;
import com.elegantmall.pojo.GoodsPojo;
import com.elegantmall.service.CartServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api/cart")
public class CartController{

    @Autowired
    private CartServiceImpl cartService;

    // 获取购物车列表
    @GetMapping("/list")
    public SaResult getCartList(
            @RequestParam String user_name
    ) {
        try {
            List<CartPojo> goodsList = cartService.getCartList(user_name);
            return SaResult.data(goodsList);
        } catch (IllegalArgumentException e) {
            return SaResult.error(e.getMessage());
        } catch (Exception e) {
            return SaResult.error("获取商品列表失败");
        }
    }

    // 加入购物车
    @PostMapping("/add")
    public SaResult addToCart(
            @RequestParam String userName,
            @RequestParam String goodsId,
            @RequestParam Integer number,
            @RequestParam Double price) {
        String result = cartService.addToCart(userName, goodsId, number, price);
        return SaResult.ok(result);
    }

    // 增加商品数量
    @PutMapping("/increase")
    public SaResult increaseNumber(
            @RequestParam String goodsId) {
        String result = cartService.increaseNumber(goodsId);
        return SaResult.ok(result);
    }

    // 减少商品数量
    @PutMapping("/decrease")
    public SaResult decreaseNumber(@RequestParam String goodsId) {
        String result = cartService.decreaseNumber(goodsId);
        return SaResult.ok(result);
    }

    // 删除购物车商品
    @DeleteMapping("/delete")
    public SaResult deleteCartItem(
            @RequestParam String user_name,
            @RequestParam String goodsId
    ) {
        String result = cartService.deleteCartItem(user_name, goodsId);
        return SaResult.ok(result);
    }

    // 更新购物车商品数量
    @PutMapping("/update")
    public SaResult updateQuantity(
            @RequestBody CartPojo cart) {
        String result = cartService.updateQuantity(cart);
        return SaResult.ok(result);
    }
}